package com.rjwh.dingdong.client.application;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.support.multidex.MultiDex;
import android.util.DisplayMetrics;

import com.aishua.lib.utils.AsLog;
import com.aishua.lib.utils.AsShardPreUtils;
import com.baidu.mobstat.StatService;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.service.HttpWebCoreService;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.FinalHttpLog;
import com.rjwh.dingdong.client.util.LogUtil;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;
import com.wby.utility.AppUtil;

import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalHttp;

public class MyApplication extends Application implements Thread.UncaughtExceptionHandler{
    public static AsShardPreUtils spUtil;
    public static MyApplication app;
    public static String versionCode;
    public static String deviceId="";
    public static int screenWidth, screenHegiht;
    public static FinalDb db;
    public static FinalHttp http;
    public static String packgeName;

    public MyApplication() {
    }

    // 单例模式获取唯一的MyApplication实例
    public static MyApplication getInstance() {
        if (null == app) {
            app = new MyApplication();
        }
        return app;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init() {
        app = this;
        boolean isDebug = isApkDebugable(this);
        AsLog.setDebug(isDebug);
        db = FinalDb.create(this, LocalConstant.CONST_APP_DB_DATABASE, isDebug);
        StatService.setDebugOn(isDebug);
        if (!isDebug)
            StatService.setOn(this, StatService.EXCEPTION_LOG);//处于relese模式就启用错误收集 debug则关闭
        spUtil = AsShardPreUtils.getInstant();
        http = new FinalHttpLog();
        http.configCharset("utf-8");
        //初始化App文件夹
        FileUtils.initFileManage(this);
        //初始化日志打印工具
        LogUtil.setIsDebu(isDebug);

        DisplayMetrics dm = new DisplayMetrics();
        dm = getResources().getDisplayMetrics();
        MyApplication.screenWidth = dm.widthPixels; // 屏幕宽（像素，如：480px）
        MyApplication.screenHegiht = dm.heightPixels; // 屏幕高（像素，如：800px）
        if (!spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_UUID).equals("")) {
            deviceId = spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_UUID);
        }
        versionCode = String.valueOf(AppUtil.GetVersionName(this));
        packgeName = getPackageName();
        LogUtil.d("packgeName:"+packgeName);
        initX5WebView();
    }

    public void initX5WebView(){
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                LogUtil.e("WEBIEW", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub

            }
        };
        QbSdk.setTbsListener(new TbsListener() {
            @Override
            public void onDownloadFinish(int i) {
                LogUtil.e("WEBIEW","onDownloadFinish");
            }

            @Override
            public void onInstallFinish(int i) {
                LogUtil.e("WEBIEW","onInstallFinish");
            }

            @Override
            public void onDownloadProgress(int i) {
                LogUtil.e("WEBIEW","onDownloadProgress:"+i);
            }
        });
        QbSdk.allowThirdPartyAppDownload(true);
        QbSdk.initX5Environment(getApplicationContext(), QbSdk.WebviewInitType.FIRSTUSE_AND_PRELOAD, cb);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        exit();
    }

    /**
     * 遍历所有仍驻在内存中的Activity并finish,再退出应用
     */
    private void exit() {
        stopService(new Intent(this, HttpWebCoreService.class));
        AppManager.getAppManager().finishAllActivity();
        System.exit(0);
    }

    /**‘
     * 重启APP
     */
    public void restApp() {
        stopService(new Intent(this, HttpWebCoreService.class));
        AppManager.getAppManager().finishAllActivity();
        Intent i = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage(getBaseContext().getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }

    private boolean isApkDebugable(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {

        }
        return false;
    }


    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        exit();
    }
}
